import os
import hashlib
import json

def calculate_file_hash(file_path):
    """Calculate and return the SHA-256 hash of the file"""
    hasher = hashlib.sha256()
    try:
        with open(file_path, 'rb') as f:
            buf = f.read()
            hasher.update(buf)
    except FileNotFoundError:
        return json.dumps({"error": "File not found"})
    return hasher.hexdigest()

def get_file_size(file_path):
    """Return the file size"""
    try:
        return os.path.getsize(file_path)
    except FileNotFoundError:
        return None

def query_hash_size(file_path):
    """Query the hash and size of the file and return it in JSON format"""
    if not os.path.exists(file_path):
        return json.dumps({"error": "File does not exist"})

    file_hash = calculate_file_hash(file_path)
    file_size = get_file_size(file_path)

    if file_hash is None or file_size is None:
        return json.dumps({"error": "Failed to get file details"})

    result = {
        "file_path": file_path,
        "hash": file_hash,
        "size": file_size
    }

    return json.dumps(result)

if __name__ == '__main__':
    import sys
    # Ensure the correct number of arguments are provided
    if len(sys.argv) != 2:
        print(json.dumps({"error": "One argument required: absolute path to the file"}))
    else:
        file_path = sys.argv[1]
        print(query_hash_size(file_path))

        
# e.g. python .\m01_file_detail.py "D:\photo\temp\IMG_3672.JPEG"